package anc.tankshooter.database;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseQuery 
{
	
	public static final String DATABASE_NAME="anc.tankshooter_database.db";
	public static final String TB_HIGHSCORES="highscores";
	
	private DatabaseHelper mHelper;
	private SQLiteDatabase mDb;
	private Context mContext;
	
	public DatabaseQuery(Context context) {
		mContext=context;
		this.mHelper=new DatabaseHelper(mContext, DatabaseQuery.DATABASE_NAME);
		mDb = mHelper.getWritableDatabase();
	}
	
	public boolean addHighScore(int level,HighScore hs){
		boolean isSuccess = false;
		try{
			String sql = "INSERT INTO "+TB_HIGHSCORES+
					"([name],[level],[score],[normal_tank],[fast_tank],[heavy_tank],[boss_tank],[time])"+
					" VALUES(?,?,?,?,?,?,?,?)";
			Cursor reader = mDb.rawQuery(sql, new String[]{hs.mName,level+"",hs.mScore+"",
															hs.mNormalTank+"",hs.mFastTank+"",
															hs.mHeavyTank+"",hs.mBossTank+"",hs.mTime+""});
			if(reader.moveToFirst())
				isSuccess = true;
			reader.close();
		}catch(Exception ex){}
		return isSuccess;
	}
	
	public ArrayList<HighScore> getHighScores(int top){
		ArrayList<HighScore> hss = new ArrayList<HighScore>();
		try{
			String sql = "SELECT * FROM "+TB_HIGHSCORES+
						" ORDER BY [score] DESC LIMIT ?";
			Cursor reader = mDb.rawQuery(sql, new String[]{top+""});
			while(reader.moveToNext()){
				HighScore hs = new HighScore();
				hs.mId = reader.getInt(0);
				hs.mName = reader.getString(1);
				hs.mLevel = reader.getInt(2);
				hs.mScore = reader.getInt(3);
				hs.mNormalTank = reader.getInt(4);
				hs.mFastTank = reader.getInt(5);
				hs.mHeavyTank = reader.getInt(6);
				hs.mBossTank = reader.getInt(7);
				hs.mTime = reader.getInt(8);
				hss.add(hs);
			}
			reader.close();
		}catch(Exception ex){}
		return hss;
	}

	
}
